/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import Conexion.Conexion;
import RRHH_MODELO.RHH_CATEGORIA_DATO;
import RRHH_MODELO.RHH_DATOS;
import RRHH_MODELO.RHH_PERSONA;
import RRHH_MODELO.RHH_PERSONA_DATOS;
import RRHH_MODELO.RHH_POSTULADO;
import RRHH_MODELO.RHH_POSTULADO_CONVOCATORIA;
import it.sauronsoftware.ftp4j.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.hibernate.validator.internal.util.CollectionHelper;


/**
 *
 * @author equipo_4
 */
@MultipartConfig
@WebServlet(name = "perfil_controller", urlPatterns = {"/perfil_controller"})
public class perfil_controller extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */      
    
    public void init( ){
      // Get the file location where it would be stored.
   }

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet perfil_controller</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet perfil_controller at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String evento = request.getParameter("evento");         
            Conexion con = new Conexion();
            switch (evento) 
            {
                case "fotoperfil":            
                    fotoperfil(request,con,response);                    
                    break;
                case "cambiarPass":            
                    cambiarPass(request,con,response);                    
                    break;
               /* case "fotodato":
                    fotodato(request,con);
                    break;*/
                case "adddatos":
                    adddatos(request,con,response);
                    break;
                case "guardar":
                    guardar(request,con,response);
                    break;
                case "postular":
                    postular(request,con);
                    break;
            }
            
            
            
        } catch (SQLException ex) {
            Logger.getLogger(perfil_controller.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (Exception ex) {
                Logger.getLogger(perfil_controller.class.getName()).log(Level.SEVERE, null, ex);
            }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void fotoperfil(HttpServletRequest request, Conexion con,HttpServletResponse response) throws SQLException, IOException,  Exception {
      
        Part part = request.getPart("file");                                              
        InputStream in = part.getInputStream();        
        int idpersona = Integer.parseInt(request.getParameter("id"));
        RHH_PERSONA per = new RHH_PERSONA(con).Buscar(idpersona);          
        String nombre = "perfil_"+part.getSubmittedFileName(); 
        long size = part.getSize();
        subirftp(in, per.getCI()+"", nombre, size,per.getFOTO());
        per.fotoperfil(nombre);        
        in.close();               
        con.Close();
    }
    

    private void subirftp(InputStream in, String ci, String nombre, long size,String old) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException
    {
        FTPClient client = new FTPClient();          
        client.connect("192.168.0.101");
        client.login("postulado","oracle123");
        
        try{
            client.createDirectory(ci);
            client.changeDirectory(ci);
        }
        catch(Exception e)
        {
            client.changeDirectory(ci);
        }
        try{
            client.deleteFile(old);
        }catch(Exception e){}                
        client.upload(nombre, in, size, 0, null);
        
        client.disconnect(false);
    }
    
    private void guardar(HttpServletRequest request, Conexion con, HttpServletResponse response) throws SQLException, IOException, ServletException, IllegalStateException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException {
        String ci=request.getParameter("ci");
        String nombre1=request.getParameter("nombre1");
        String nombre2=request.getParameter("nombre2");
        String apepat=request.getParameter("apepat");
        String apemat=request.getParameter("apemat");
        String telf=request.getParameter("telf");
        String email=request.getParameter("email");
        Part part = request.getPart("curr");
        InputStream in = part.getInputStream();
        String nombre = "curriculum_"+part.getSubmittedFileName(); 
        long size = part.getSize();        
        RHH_PERSONA per = new RHH_PERSONA(con).Buscar(ci);
        subirftp(in, per.getCI()+"", nombre, size,per.getCURRICULUM());
        in.close();
        per.setPRIMER_NOMBRE(nombre1);
        per.setSEGUNDO_NOMBRE(nombre2);
        per.setPRIMER_APELLIDO(apepat);
        per.setSEGUNDO_APELLIDO(apemat);
        per.setTELEFONO(telf);
        per.setEMAIL(email);
        per.setCURRICULUM(nombre);        
        in.close();
        per.update();        
        List<RHH_CATEGORIA_DATO> listac = new RHH_CATEGORIA_DATO(con).Todos();
                
        for (int j = 0; j < listac.size(); j++) 
        {
            List<RHH_PERSONA_DATOS> lista = new RHH_PERSONA_DATOS(con).TodosXPERSONA(per.getID(),listac.get(j).getID());
            for (int i = 0; i < lista.size(); i++) 
            {
                RHH_DATOS dato = new RHH_DATOS(con).BuscarXid(lista.get(i).getID_DATOS());
                if(dato.getTIPO()==0)
                {
                    String actual = request.getParameter(dato.getID()+"");
                    if(!actual.equals(""))
                    {
                        RHH_PERSONA_DATOS pd = new RHH_PERSONA_DATOS(actual, dato.getID(),per.getID() , null);
                        pd.setCon(con);
                        pd.Actualizar();
                    }
                }
                else
                {
                    part = request.getPart(dato.getID()+"");
                    
                    if(!part.getSubmittedFileName().equals(""))
                    {
                        in = part.getInputStream();
                        nombre = "doc_"+part.getSubmittedFileName(); 
                        size = part.getSize();
                        RHH_PERSONA_DATOS pd = new RHH_PERSONA_DATOS(con).BuscarXid(per.getID(), dato.getID());
                        subirftp(in, per.getCI()+"", nombre, size,pd.getDATO());
                        pd.setDATO(nombre);
                        pd.setCon(con);
                        pd.Actualizar();                      
                        in.close();
                    }
                }
            }
        }
        con.Close();
    }

    private void adddatos(HttpServletRequest request, Conexion con, HttpServletResponse response) throws SQLException, IOException, ServletException, IllegalStateException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException {
        int id = Integer.parseInt(request.getParameter("id"));
        RHH_PERSONA per = new RHH_PERSONA(con).Buscar(id);
        
        List<RHH_CATEGORIA_DATO> listac = new RHH_CATEGORIA_DATO(con).Todos();
        for (int j = 0; j < listac.size(); j++) 
        {
            List<RHH_DATOS> lista_vacios = new RHH_DATOS(con).TodosXNotinPERSONA(per.getID(),listac.get(j).getID());
            for (int i = 0; i < lista_vacios.size(); i++) 
            {
                if(lista_vacios.get(i).getTIPO()==0)
                {
                    String actual = request.getParameter(lista_vacios.get(i).getID()+"");
                    if(!actual.equals(""))
                    {
                        RHH_PERSONA_DATOS pd = new RHH_PERSONA_DATOS(actual, lista_vacios.get(i).getID(),id , null);
                        pd.setCon(con);
                        pd.Insertar();
                    }
                }
                else
                {
                    Part part = request.getPart(lista_vacios.get(i).getID()+"");
                    if(!part.getSubmittedFileName().equals(""))
                    {
                        InputStream in = part.getInputStream();                                                              
                        String nombre = "doc_"+part.getSubmittedFileName(); 
                        long size = part.getSize();
                        subirftp(in, per.getCI()+"", nombre, size,"");
                        RHH_PERSONA_DATOS pd = new RHH_PERSONA_DATOS(nombre, lista_vacios.get(i).getID(),id , null);
                        pd.setCon(con);
                        pd.Insertar();                       
                    }
                }
            }
        }    
        con.Close();
    }

    private void postular(HttpServletRequest request, Conexion con) throws SQLException {
        int tipo = Integer.parseInt(request.getParameter("tipo"));
        int conv = Integer.parseInt(request.getParameter("conv"));
        int post = Integer.parseInt(request.getParameter("post"));
        if(tipo==0)
        {
            RHH_POSTULADO_CONVOCATORIA postu = new RHH_POSTULADO_CONVOCATORIA(post, conv);
            postu.setCon(con);
            postu.Insertar();
        }
        else
        {
            RHH_POSTULADO_CONVOCATORIA postu = new RHH_POSTULADO_CONVOCATORIA(post, conv);
            postu.setCon(con);
            postu.Eliminar();
        }
        con.Close();        
    }

    private void cambiarPass(HttpServletRequest request, Conexion con, HttpServletResponse response) throws IOException, SQLException {
        RHH_POSTULADO post = new RHH_POSTULADO(con);
        post=post.BuscarXid(Integer.parseInt(request.getParameter("id")));
        post.cambiarPass(request.getParameter("pass"));        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");
        response.getWriter().write("true");
        con.Close();
    } 
}
